<?php

namespace addons\booking\controller;

use addons\booking\model\Coupon as CouponModel;
use addons\booking\model\UserCoupon;
use addons\booking\model\CouponCondition;
use addons\booking\model\House;
use addons\booking\model\Goods;
use think\Db;
use addons\booking\model\Collect;
use addons\booking\library\IntCode;

class Coupon extends Base
{

    protected $noNeedLogin = ['couponList', 'couponDetail'];

    /**
     * 领取优惠券
     */
    public function drawCoupon()
    {
        $coupon_id = $this->request->post('id');
        if (!$coupon_id) {
            $this->error('参数错误');
        }
        $coupon_id = IntCode::decode($coupon_id);
        if (!$coupon_id) {
            $this->error('参数错误');
        }
        $model = new CouponModel();
        try {
            $row = $model->getCoupon($coupon_id)
                ->checkCoupon()
                ->checkOpen()
                ->checkNumber()
                ->checkMyNumber($this->auth->id)
                ->checkReceiveTime();

            Db::startTrans();
            try {
                list($begin_time, $expire_time) = $row->getUseTime();
                //检测没问题，可领取
                (new UserCoupon())->save([
                    'coupon_id'   => $coupon_id,
                    'user_id'     => $this->auth->id,
                    'begin_time'  => $begin_time,
                    'expire_time' => $expire_time
                ]);
                $row->setInc('received_num');
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw new \Exception($e->getMessage());
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('领取优惠券成功！');
    }

    //优惠券列表
    public function couponList()
    {
        $param = $this->request->param();
        $param['is_private'] = 'no';
        $param['is_open'] = 1;
        $param['num'] = 15;
        $list = CouponModel::tableList($param);
        //已经登录，渲染已领的优惠券
        $coupon_ids = [];
        if ($this->auth->isLogin()) {
            $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id');
        }
        $newList = [];
        foreach ($list as $key => $item) {
            CouponModel::render($item, $coupon_ids);
            $item->hidden(['received_num', 'give_num']);
            $item->id = IntCode::encode($item->id);
            $newList[] = $item;
        }
        $this->success('获取成功！', [
            'data'     => $newList,
            'has_more' => $list->hasPages()
        ]);
    }

    /**
     * 优惠券详情
     */
    public function couponDetail()
    {
        $coupon_id = $this->request->param('id');
        $id = IntCode::decode($coupon_id);
        if (!$id) {
            $this->error('参数错误');
        }
        $row = CouponModel::where('id', $id)->where('is_open', 1)->find();
        if ($row) {
            //优惠券可使用的房间
            $conditions = CouponCondition::where('id', 'IN', $row['condition_ids'])->select();

            $row->goods = Goods::where(function ($query) use ($conditions) {
                foreach ($conditions as $item) {
                    if ($item['type'] == 6) {
                        $query->where('id', $item['content']);
                    } elseif ($item['type'] == 3 || $item['type'] == 4) {
                        $query->whereOr('1=1');
                    }
                }
            })->limit(10)->select();

            $field = 't.name as type_name,';
            $field .= 'h.id,h.market_price,h.tag_config_ids,h.name,h.views,h.area,h.livenums,h.status,h.images,h.createtime,';
            $field .= 'GROUP_CONCAT(c.name) tag_names,';
            $field .= "if(d.price>0,d.price,h.price) as house_price";

            $time = strtotime(date('Y-m-d'));

            $row->house = House::field($field)
                ->alias('h')
                ->join('booking_config c', 'FIND_IN_SET(c.id,h.tag_config_ids)', 'LEFT')
                ->join('booking_config t', 'h.type_config_id=t.id', 'LEFT')
                ->join('booking_calendar d', 'd.house_id=h.id AND d.day_time=' . $time, 'LEFT')
                ->where(function ($query) use ($conditions) {
                    foreach ($conditions as $item) {
                        switch ($item['type']) { //1房间,2门店,3新用户,4老用户
                            case 1:
                                $query->where('h.id', 'in', $item['content']);
                                break;
                            case 2:
                                $query->whereOr('h.store_id', 'in', $item['content']);
                                break;
                            case 3:
                            case 4:
                            case 5:
                                $query->whereOr('1=1');
                                break;
                        }
                    }
                })->group('h.id')->limit(10)->select();

            //已经登录，渲染已领的优惠券
            $coupon_ids = [];
            if ($this->auth->isLogin()) {
                $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id');
                Collect::render($row->house, $this->auth->id, 0);
            }
            CouponModel::render($row, $coupon_ids);
            $row->id = $coupon_id;
            $this->success('获取成功！', $row);
        }
        $this->error('记录未找到');
    }

    /**
     * 我的优惠券列表
     */
    public function myCouponList()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $list = UserCoupon::tableList($param);
        foreach ($list as $item) {
            $item->coupon_id = IntCode::encode($item->coupon_id);
            if ($item->coupon) {
                $item->coupon->id = $item->coupon_id;
                $item->expired = $item->expire_time < time();
                $item->begin = $item->begin_time < time();
            }
        }
        $this->success('获取成功！', $list);
    }
}
